package main.java.org.gravity;

/*
 * Author: Fami
 * version: 0.1
 * File: procChecker.java
 * Repo: https://code.google.com/p/osprocchecker/
 * License: MIT License
 * Desc: Class for scanning os process
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.gravity.Function;


public class procScanner {
	
	public static String winScanner(String procName){

		String line = "";
		String patternVals = "";
		String[] myStringArray  = new String[1000];
		int counter = 0;
		Process p;
		
		try {
			p = Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
			BufferedReader input =  new BufferedReader(new InputStreamReader(p.getInputStream()));
			
			while ((line = input.readLine()) != null) {
				
				if(line.contains(procName) ){
					// 1.0 - get 2 values,  regular expression
					Pattern pattern = Pattern.compile("(\\w+?.*)\\s+(\\w+?)\\s+(\\w+?)\\s+(\\w+?)\\s+(\\w+?.*)");
					Matcher matcher = pattern.matcher(line);
					
					// 2.0 - Store the Process and PID in the array
					while (matcher.find()){
						patternVals = matcher.group(1)+":"+matcher.group(2);
						System.out.println(counter+": "+patternVals);
						myStringArray[counter] = patternVals;
						counter ++;
					}

					OSProcChecker.writeOut(Function.dir(), "winProcChecker_log.log", "Checker Status:"+procName+" is running. \r\n"+line+"\n");
				}			
			}		
			input.close();

		
		} catch (IOException e) {
			System.out.println("Execution fail, due to: \n"+e);
			e.printStackTrace();
		}
		
		//3.0 Filter the the array values for return values
		StringBuffer sb = new StringBuffer("");
		
		for (int x = 0; x < myStringArray.length ; x ++){
			if (myStringArray[x]!=null){
				sb.append(x+": " + myStringArray[x]+"\n");
			}
		}
		//System.out.println(sb.toString());
		return sb.toString();

	}

}
